package com.meiyuetao.myt.customer.service;

import lab.s2jh.core.dao.BaseDao;
import lab.s2jh.core.service.BaseService;
import lab.s2jh.core.service.Validation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.meiyuetao.myt.customer.dao.CustomerProfileDao;
import com.meiyuetao.myt.customer.dao.ScoreDao;
import com.meiyuetao.myt.customer.entity.CustomerProfile;
import com.meiyuetao.myt.customer.entity.Score;

@Service
@Transactional
public class ScoreService extends BaseService<Score, Long> {

    @Autowired
    private ScoreDao scoreDao;

    @Autowired
    private CustomerProfileDao customerProfileDao;

    @Override
    protected BaseDao<Score, Long> getEntityDao() {
        return scoreDao;
    }

    @Override
    public Score save(Score entity) {
        // 更新客户积分相关信息
        CustomerProfile customerProfile = entity.getCustomerProfile();
        Validation.isTrue(customerProfile != null, "积分必须指定所属客户");
        Validation.isTrue(entity.getScoreAmount() != null, "必须指定分额");
        if (entity.isNew()) {
            // Assert.notNull(customerProfile);// 必须指定积分所属客户
            customerProfile = customerProfileDao.findOne(customerProfile.getId());
            if (!entity.getScorePending()) {
                // 不是待定积分, 同步只至客户信息积分字段
                if (customerProfile.getScore() == null) {
                    customerProfile.setScore(entity.getScoreAmount());
                } else {
                    int score = customerProfile.getScore() + entity.getScoreAmount();
                    customerProfile.setScore(score);
                }

            } else {
                // 是待定积分, 同步至客户信息冻结积分字段
                if (customerProfile.getFrozenScore() == null) {
                    customerProfile.setFrozenScore(entity.getScoreAmount());
                } else {
                    int frozenScore = customerProfile.getFrozenScore() + entity.getScoreAmount();
                    customerProfile.setFrozenScore(frozenScore);
                }
            }

            customerProfileDao.save(customerProfile);
        }

        return super.save(entity);
    }
}